//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
var selectgood = [];
var allGoods = [];
var selectmap = {};
var commodityAttr = [];
var attrValueList = [];
var selectNum = '';
var cartpoint = '0';
var currentPrice = '';
var currentNum = '';
var partIndex = 0
var partIndex2 = 10
var newarr = []
var partarr = []
var start = 0
var end = 10
// const createRecycleContext = require('miniprogram-recycle-view')//小程序长列表渲染组件
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uid: "",
    businessId: 0,
    isAsc: false,
    pageIndex: 1,
    allGoodsData: [],
    sjId: '',
    state: '',
    showBy: 'SaleNumber',
    // 删除
    startX: 0,
    startY: 0,
    // input默认是1
    num: 0,
    // 使用data数据对象设置样式名
    minusStatus: 'disabled',
    //总数量
    // cart_count: 0,
    // //总金额
    // total_price: 0.00,
    // // 邮费
    // total_yf: 0.00,
    // // 订单信息字符串
    // orderStr: "",
    // // 购物车id
    // cartId: 0,

    // 商品详情
    isBuluoArea: 0,
    isEnjoyArea: 0,
    resultData: {},
    goodsId: 0,
    // 购买，底部弹出
    chooseFlag: true,
    // 购物车，底部弹出
    chooseFlag0: true,
    //轮播
    goodsLunbo: [],
    // 规格
    modelStr0: '',
    // 导航
    map: "",
    firstIndex: "",
    toView: 'green',
    show: false, //客户选择自提或者邮寄的弹框
    buttons: [{
      type: 'default',
      text: '客户自提',
      value: 0
    },
    {
      type: 'primary',
      text: '买家邮寄',
      value: 1
    }
    ],
    buttons2: [
      { //底部购物车
        type: 'default',
        text: '扫一扫',
        value: 0
      },
      {
        type: 'primary',
        text: '清空购物车',
        value: 1
      }
    ],
    // 提交订单
    buyGoods: "",
    peisongyoufei: "",
    // 搜索
    searchWhat: '',
    hiddensubmit: true,
    nocancel: false,
    // 填写价格-弹框
    peisongyoufei: '',
    hiddensubmit1: true,
    // nocancel: false,
    hiddensubmit2: true,
    nocance2: false,
    showChangeNum: true, //输入购买数量的弹框

    /////////////////
    num2: "",
    index: 0,
    text: "生成二维码",
    partArr: [],
    timer: null,
    powerFlag: true,
    show2: false,//点击底部购物车
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.getStorageSync('uid')
    if (options.businessId) {
      this.setData({
        businessId: options.businessId,
        text: "立即支付"
      })
    }
    // console.log(options.businessId);
    selectgood = [],
      this.setData({
        uid: wx.getStorageSync('uid'),
        // businessId: options.businessId,
        goodsId: options.goodsId,
        selectgood: selectgood,
      })
    this.GetGoodsByBusinessID();
  },
  // 全部商品
  GetGoodsByBusinessID: function () {
    var that = this;

    if (this.data.businessId) {
      var id = this.data.businessId;
    } else {
      var id = this.data.uid;
    }
    var isAsc = this.data.isAsc;
    var pageIndex = this.data.pageIndex;
    var showBy = this.data.showBy;
    var state = this.data.state;
    var allGoodsData = this.data.allGoodsData;
    var sjId = this.data.sjId;
    if (pageIndex == 1) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetGoodsByBusinessID&BID=" + id + "&PageSize=2000&PageIndex=" + pageIndex + "&IsAsc=" + isAsc + "&OrderBy=" + showBy),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        console.log(json)
        for (var i = 0; i < json.length; i++) {
          json[i].BuyNum = '0';
          allGoodsData.push(json[i])
        }
        allGoods = allGoodsData
        start = 0
        end = 10
        partarr = allGoods.slice(start, end) //如果列表过长，只渲染前十个
        if (allGoods.length > 150) {
          that.setData({
            allGoods: partarr,
          })
        } else {
          that.setData({
            allGoods: allGoods,
          })
        }
        that.setData({
          allGoods: partarr,
        })
        // that.partArrFn()
        if (json.length == 2000) {
          that.setData({
            state: 'loadMore',
          })
        } else if (json.length == 0 && pageIndex == 1) {
          that.setData({
            state: 'noMore',
          })
        } else if (json.length < 2000) {
          that.setData({
            state: 'noMore',
          })
        } else if (json.length == 0 && pageIndex > 1) {
          that.setData({
            state: 'noMore',
          })
        }
        wx.hideLoading()
      }
    })
  },

  // 窃取部分数组内容
  partArrFn: function () {
    partArr = allGoods.slice(partIndex, partIndex2);
    partIndex = partIndex2
    partIndex2 += 10
    newarr = newarr.concat(partArr)
    // partArr = partArr.concat(partArr)
    this.setData({
      partArr: newarr
    })
    console.log(newarr);
    // partIndex += 10
  },

  // 搜索输入框
  inputTap: function (e) {
    this.setData({
      searchWhat: e.detail.value,
    })
  },

  // 扫一扫
  scanTap: function () {
    var that = this;
    var uid = this.data.uid;
    // 扫一扫判断是否登录
    if (!uid) {
      wx.redirectTo({
        url: '/packageA/login/login',
      })
    }
    this.setData({
      show2:false//隐藏购物车
    })
    wx.scanCode({
      // onlyFromCamera: true,
      success(res) {
        var result = res.result;
        var isFind
        console.log("0000");
        console.log(result)
        for (var i = 0; i < allGoods.length; i++) {
          // clearTimeout(time)
          // var time = setTimeout(() => {
          if (allGoods[i].GoodsLableCode == result) { //判断产品是否存在
            isFind = i
            break
          }
          console.log(isFind);
        }
        if (isFind) {
          var map = allGoods[isFind];
          console.log(map)
          if (map.stocknum == '0') {
            wx.showModal({
              title: '提示',
              content: '暂无库存，该产品已易完',
              showCancel: false
            })
          }
          var flag = '0';
          selectgood.forEach(item => {
            if (map.ID == item.GoodsID) {
              flag = '1';
              item.BuyNum = parseInt(item.BuyNum) + 1;
              allGoods[i].BuyNum = item.BuyNum;
            }
          });
          if (flag == '0') {
            var tempmap = {};
            tempmap.GoodsID = map.ID;
            tempmap.GoodsName = map.GoodsName;
            tempmap.GoodsZsImg = map.ImagesZhanshi;
            tempmap.Price = map.PresentPrice;
            tempmap.BuyNum = '1';
            tempmap.Model = "";
            tempmap.stockNum = map.stocknum;
            var temparray = [tempmap];
            selectgood = temparray.concat(selectgood)
            console.log(selectgood)
            allGoods[i].BuyNum = tempmap.BuyNum;
          }
          that.setData({
            allGoods: allGoods,
            chooseFlag0: false,
            selectgood: selectgood,
            // showModal: true,
          })
        } else if (isFind == undefined) {
          wx.showToast({
            title: '未查询到该条码产品',
            icon: "none"
          })
        }

        console.log(allGoods)

        that.re_count(); //重新计算
      },
      fail(err) {
        console.log(err);
      },
    })
  },
  // 点击清空购物车--弹框
  bindClear: function () {
    var that = this;
    var hiddensubmit = this.data.hiddensubmit;
    that.setData({
      hiddensubmit: !this.data.hiddensubmit,
      show2:false
    })
  },

  // 弹框-取消清空购物车
  cancel: function () {
    this.setData({
      hiddensubmit: true
    });
  },
  // 确定---清空购物车
  confirm: function (e) {
    var that = this;
    var clearSelectgood = [];
    selectgood = [];
    for (var i = 0; i < allGoods.length; i++) {
      allGoods[i].BuyNum = 0;
      allGoods[i].isselect = 0;
    }
    that.setData({
      selectgood: clearSelectgood,
      allGoods: allGoods,
    })
    // console.log(selectgood)
    that.re_count(); //重新计算
    this.setData({
      hiddensubmit: true,
      chooseFlag0: true,
      // showModal: false,
    });
  },

  // /* 点击减号 */
  bindMinus: function (e) {
    var allGoodsData = this.data.allGoodsData,
      curBindex = e.currentTarget.dataset.bindex,
      curIndex = e.currentTarget.dataset.index;
    var map = allGoods[curIndex];
    var flag = '0';
    if (map.BuyNum == '0') {
      return;
    }
    for (var i = 0; i < selectgood.length; i++) {
      var item = selectgood[i];
      console.log(item.GoodsID)
      if (map.ID == item.GoodsID) {
        flag = '1';
        if (item.BuyNum == '1') {
          selectgood.splice(i, 1);
          allGoods[curIndex].BuyNum = '0';
        } else {
          item.BuyNum = parseInt(item.BuyNum) - 1;
          allGoods[curIndex].BuyNum = item.BuyNum;
        }
      }
    }
    this.setData({
      allGoods: allGoods,
    })
    console.log(allGoods)
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = allGoodsData.BuyNum <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.re_count(); //重新计算
  },

  // 点击加号
  bindPlus: function (e) {
    var allGoodsData = this.data.allGoodsData,
      curBindex = e.currentTarget.dataset.bindex,
      curIndex = e.currentTarget.dataset.index;
    var map = allGoods[curIndex];
    console.log(map);
    if (map.stocknum == '0') {
      wx.showModal({
        title: '提示',
        content: '暂无库存，该产品已易完',
        showCancel: false
      })
      return;
    }
    var flag = '0';
    selectgood.forEach(item => {
      // console.log(item.GoodsID)
      if (map.ID == item.GoodsID) {
        flag = '1';
        if (map.stocknum < parseInt(item.BuyNum) + 1) {
          wx.showModal({
            title: '提示',
            content: '库存不足',
            showCancel: false
          })
          return;
        }
        item.BuyNum = parseInt(item.BuyNum) + 1;
        // console.log(item.BuyNum)
        allGoods[curIndex].BuyNum = item.BuyNum;
      }
    });
    if (flag == '0') {
      var tempmap = {};
      tempmap.GoodsID = map.ID;
      tempmap.GoodsName = map.GoodsName;
      tempmap.GoodsZsImg = map.ImagesZhanshi;
      tempmap.Price = map.PresentPrice;
      tempmap.BuyNum = '1';
      tempmap.Model = "";
      tempmap.stockNum = map.stocknum;
      var temparray = [tempmap];
      console.log(temparray);
      selectgood = temparray.concat(selectgood)
      console.log(selectgood)
      allGoods[curIndex].BuyNum = tempmap.BuyNum;
      // console.log(tempmap)
    }
    this.setData({
      allGoods: allGoods,
    })
    // console.log(allGoods)

    // 不作过多考虑自增1
    // allGoodsData.BuyNum++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = allGoodsData.BuyNum < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      allGoodsData: allGoodsData,
    });
    this.re_count(); //重新计算
  },

  // /* 点击减号add */
  bindMinusadd: function (e) {
    if (parseInt(selectNum) - 1 < 0) {
      return;
    }
    selectNum = parseInt(selectNum) - 1;
    this.setData({
      selectNum: selectNum,
    })


    this.setData({
      selectNum: selectNum,
    })
    // console.log(allGoods)
    // 只有大于一件的时候，才能normal状态，否则disable状态
  },

  // // 点击加号add
  bindPlusadd: function (e) {
    // console.log(selectmap)
    if (currentNum < parseInt(selectNum) + 1) {
      wx.showModal({
        title: '提示',
        content: '库存不足',
        showCancel: false
      })
      return;
    }
    selectNum = parseInt(selectNum) + 1;
    this.setData({
      selectNum: selectNum,
    })

  },
  // /* 输入框事件 */
  bindManual: function (e) {
    console.log(e);
    var curIndex = e.currentTarget.dataset.index;
    var map = selectgood[curIndex];
    // console.log(map)
    if (map.stockNum < parseInt(selectgood[curIndex].BuyNum) + 1) {
      wx.showModal({
        title: '提示',
        content: '库存不足',
        showCancel: false
      })
      return;
    }
    selectgood[curIndex].BuyNum = parseInt(selectgood[curIndex].BuyNum) + 1;
    allGoods.forEach(item => {
      // console.log(item.GoodsID)
      if (map.GoodsID == item.ID) {
        if (item.IsSimpleLoad == '1') {
          item.BuyNum = parseInt(item.BuyNum) + 1;

        }

      }
    });

    this.setData({
      selectgood: selectgood,
      allGoods: allGoods,
    })
    // console.log(selectgood)

    this.re_count(); //重新计算
  },


  // 购买数量的点击
  shurushuliang(e) {
    console.log(e);
    this.setData({
      showChangeNum: false,
      index: e.currentTarget.dataset.index
    })
  },


  // 获取输入框的值
  inputNum(e) {
    this.setData({
      num2: e.detail.value
    })
    // var map = allGoods[curIndex];
    // console.log(map);
    // console.log(e.detail.value);
    // if(e.detail.value>map.stockNum){
    //   console.log("00000");

    // }

  },
  // 购买数量的弹框取消
  cancel2() {
    this.setData({
      showChangeNum: true,
      num2: ""
    })
  },
  // 购买数量的确定
  confirm2() {
    var num2 = this.data.num2
    var allGoodsData = this.data.allGoodsData,
      // curBindex = e.currentTarget.dataset.bindex,
      // curIndex = e.currentTarget.dataset.index;
      curIndex = this.data.index;
    var map = allGoods[curIndex];
    console.log(map);
    if (map.stocknum == '0') {
      wx.showModal({
        title: '提示',
        content: '暂无库存，该产品已易完',
        showCancel: false
      })
      return;
    }
    console.log(num2);
    console.log(map.stocknum);
    if (parseInt(num2) <= 0) {
      console.log("0000");
      wx.showModal({
        title: '提示',
        content: '请输入正确内容！',
        showCancel: false
      })
      return
    }
    if (parseInt(num2) > parseInt(map.stocknum)) {
      wx.showModal({
        title: '提示',
        content: '库存不足',
        showCancel: false
      })
      return;
    }
    var flag = '0';
    selectgood.forEach(item => {
      // console.log(item.GoodsID)
      if (map.ID == item.GoodsID) {
        flag = '1';
        // if (map.stocknum < parseInt(item.BuyNum) + 1) {
        //   wx.showModal({
        //     title: '提示',
        //     content: '库存不足',
        //     showCancel: false
        //   })
        //   return;
        // }

        // item.BuyNum = parseInt(item.BuyNum) + 1;
        item.BuyNum = parseInt(num2);
        // console.log(item.BuyNum)
        allGoods[curIndex].BuyNum = item.BuyNum;
      }
    });
    if (flag == '0') {
      var tempmap = {};
      tempmap.GoodsID = map.ID;
      tempmap.GoodsName = map.GoodsName;
      tempmap.GoodsZsImg = map.ImagesZhanshi;
      tempmap.Price = map.PresentPrice;
      tempmap.BuyNum = num2;
      tempmap.Model = "";
      tempmap.stockNum = map.stocknum;
      var temparray = [tempmap];
      console.log(temparray);
      selectgood = temparray.concat(selectgood)
      console.log(selectgood)
      allGoods[curIndex].BuyNum = tempmap.BuyNum;
      // console.log(tempmap)
    }
    this.setData({
      allGoods: allGoods,
    })
    // console.log(allGoods)

    // 不作过多考虑自增1
    // allGoodsData.BuyNum++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = allGoodsData.BuyNum < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      allGoodsData: allGoodsData,
      showChangeNum: true,
      num2: ""
    });
    this.re_count(); //重新计算
  },



  /* 输入框事件 */
  bindManual1: function (e) {
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      var num = e.detail.value;
      var curIndex = e.currentTarget.dataset.index;
      var allGoodsData = this.data.allGoodsData;
      var map = selectgood[curIndex];
      console.log(map);
      if (map.stockNum < parseInt(num)) {
        wx.showModal({
          title: '提示',
          content: '库存不足',
          showCancel: false
        })
        this.setData({
          selectgood: selectgood,
        })
        return;
      }
      this.setData({
        num: num,
        allGoodsData: allGoodsData,
      });
      // console.log(map)
      selectgood[curIndex].BuyNum = parseInt(num);
      allGoods.forEach(item => {
        // console.log(item.GoodsID)
        if (map.GoodsID == item.ID) {
          if (item.IsSimpleLoad == '1') {
            item.BuyNum = parseInt(num);
          }
        }
      });

      this.setData({
        selectgood: selectgood,
        allGoods: allGoods,
      })
      this.re_count(); //重新计算
    }, 1000);
    // var num = e.detail.value;
    // var curIndex = e.currentTarget.dataset.index;
    // var allGoodsData = this.data.allGoodsData;
    // var map = selectgood[curIndex];
    // console.log(map);



    // if (map.stockNum < parseInt(num)) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '库存不足',
    //     showCancel: false
    //   })
    //   return;
    // }
    // this.setData({
    //   num: num,
    //   allGoodsData: allGoodsData,
    // });



    // // console.log(map)

    // selectgood[curIndex].BuyNum = parseInt(num);
    // allGoods.forEach(item => {
    //   // console.log(item.GoodsID)
    //   if (map.GoodsID == item.ID) {
    //     if (item.IsSimpleLoad == '1') {
    //       item.BuyNum = parseInt(num);

    //     }

    //   }
    // });

    // this.setData({
    //   selectgood: selectgood,
    //   allGoods: allGoods,
    // })
    // // console.log(selectgood)

    // this.re_count(); //重新计算
  },
  // /* 点击减号 */
  bindMinuscart: function (e) {
    var curBindex = e.currentTarget.dataset.bindex;
    var curIndex = e.currentTarget.dataset.index;
    var map = selectgood[curIndex];

    if (map.BuyNum == '1') {
      selectgood.splice(curIndex, 1);
    } else {
      selectgood[curIndex].BuyNum = parseInt(selectgood[curIndex].BuyNum) - 1;
    }
    var flag = '0';
    for (var i = 0; i < allGoods.length; i++) {
      var item = allGoods[i];
      // console.log(item.ID)
      if (map.GoodsID == item.ID) {
        flag = '1';
        if (item.BuyNum == 1) {
          allGoods[i].BuyNum = '0';
        } else {
          allGoods[i].BuyNum = parseInt(item.BuyNum) - 1;
        }
      }
    }
    for (var k = 0; k < allGoods.length; k++) {
      var tempMap = allGoods[k];
      allGoods[k].isselect = '0';
      for (var j = 0; j < selectgood.length; j++) {
        if (tempMap.ID == selectgood[j].GoodsID) {
          allGoods[k].isselect = '1';
        }
      }
    }
    this.setData({
      allGoods: allGoods,
      selectgood: selectgood,
    })
    // console.log(allGoods)
    // console.log(allGoods)
    this.re_count(); //重新计算
  },
  // // 点击加号
  bindPluscart: function (e) {
    var curIndex = e.currentTarget.dataset.index;
    var map = selectgood[curIndex];
    // console.log(map)
    if (map.stockNum < parseInt(selectgood[curIndex].BuyNum) + 1) {
      wx.showModal({
        title: '提示',
        content: '库存不足',
        showCancel: false
      })
      return;
    }
    selectgood[curIndex].BuyNum = parseInt(selectgood[curIndex].BuyNum) + 1;
    allGoods.forEach(item => {
      // console.log(item.GoodsID)
      if (map.GoodsID == item.ID) {
        if (item.IsSimpleLoad == '1') {
          item.BuyNum = parseInt(item.BuyNum) + 1;

        }

      }
    });

    this.setData({
      selectgood: selectgood,
      allGoods: allGoods,
    })
    // console.log(selectgood)

    this.re_count(); //重新计算
  },

  // 底部弹出商品详情
  chooseTap0: function (e) {
    var that = this;
    var allGoodsData = this.data.allGoodsData;
    var curIndex = e.currentTarget.dataset.index;
    commodityAttr = [];
    attrValueList = [];
    selectNum = '0';
    selectmap = allGoods[curIndex];
    commodityAttr = this.endModelArr(allGoods[curIndex].NewModels);
    currentNum = selectmap.stocknum;
    currentPrice = selectmap.PresentPrice;
    // console.log(selectmap)
    // console.log(commodityAttr)
    // console.log(allGoods)
    this.setData({
      chooseFlag: !this.data.chooseFlag,
      commodityAttr: commodityAttr,
      selectmap: selectmap,
      selectNum: selectNum,
      currentNum: currentNum,
      currentPrice: currentPrice,
    });
    // console.log(currentPrice)
    // console.log(currentNum)
    this.setData({
      includeGroup: commodityAttr
    });
    this.distachAttrValue(commodityAttr);

    // 只有一个属性组合的时候默认选中 
    // console.log(this.data.attrValueList);
    if (this.data.commodityAttr.length == 1) {
      for (var i = 0; i < this.data.commodityAttr[0].attrValueList.length; i++) {
        this.data.attrValueList[i].selectedValue = this.data.commodityAttr[0].attrValueList[i].attrValue;
      }

      this.setData({
        attrValueList: this.data.attrValueList
      });
    }

  },
  // 请选择颜色规格底部弹出       
  chooseTap1: function () {
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  // 点击购物车底部弹出       
  chooseTap2: function (str) {
    this.setData({
      chooseFlag0: !this.data.chooseFlag0,
      selectgood: selectgood,
      show2: true
      // showModal: true,
    });

  },
  preventTouchMove: function () {

  },
  // 点击蒙版关闭弹框
  inow(e) {
    var id = e.currentTarget.dataset.id;
    if (id == 1) {
      this.setData({
        chooseFlag0: true,
        // showModal: false
      })
    }
  },
  // 
  iconClearTap: function () {
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  // 以下为商品规格相关函数
  endModelArr: function (str) {
    // console.log(str)
    // |颜色,红;尺码,x-库存-部落价-市场价
    if (typeof (str) !== "string") return;
    var arr = []; //声明一个空数组用于返回
    var arr1 = str.split("|"); //第一次截取，通过“ | ”截取
    for (var i = 0; i < arr1.length; i++) {
      var temparr = arr1[i].split("-"); //颜色,红;尺码,x-库存-部落价-市场价

      var obj = {
        attrValueList: [],
        GoodsID: selectmap.ID,
        price: temparr[2],
        stockNum: temparr[1],
        skukey: '',
      };
      //声明一个对象 保存第一层数据
      var arr2 = temparr[0].split(";"); //第二次截取，通过“ ； ”截取 颜色,红;尺码,x
      for (var j = 0; j < arr2.length; j++) {
        var arr3 = arr2[j].split(","); //第三次截取，通过“ ， ”截取
        var objs = {}; //声明一个对象，保存最底层数据
        objs.attrKey = arr3[0]; //添加key
        objs.attrValue = arr3[1]; //添加value

        // for (var k = 0; k < arr3.length; k++) {
        //   if (arr3[1].indexOf("-") !== -1) { //去除“ - ”后无用的字符
        //     arr3[1] = arr3[1].substring(0, arr3[1].indexOf("-"))
        //   }

        // }
        obj.attrValueList.push(objs); //保存key和value
      }
      for (var k = 0; k < obj.attrValueList.length; k++) {

        if (obj.skukey.length < 1) {
          obj.skukey = obj.attrValueList[k].attrKey + ',' + obj.attrValueList[k].attrValue
        } else {
          obj.skukey = obj.skukey + ';' + obj.attrValueList[k].attrKey + ',' + obj.attrValueList[k].attrValue
        }
      }
      // console.log(obj);
      arr.push(obj); //保存所有的key和value
    }
    return arr;
  },
  // 
  distachAttrValue: function (commodityAttr) {
    /** 
    将后台返回的数据组合成类似 
    { 
    attrKey:'型号', 
    attrValueList:['1','2','3'] 
    } 
    */
    // 把数据对象的数据（视图使用），写到局部内 
    attrValueList = [];
    // 遍历获取的数据 
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
        var attrIndex = this.getAttrIndex(commodityAttr[i].attrValueList[j].attrKey, attrValueList);
        // console.log('属性索引', attrIndex); 
        // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置 
        if (attrIndex >= 0) {
          // 如果属性值数组中没有该值，push新值；否则不处理 
          if (!this.isValueExist(commodityAttr[i].attrValueList[j].attrValue, attrValueList[attrIndex].attrValues)) {
            attrValueList[attrIndex].attrValues.push(commodityAttr[i].attrValueList[j].attrValue);
          }
        } else {
          attrValueList.push({
            attrKey: commodityAttr[i].attrValueList[j].attrKey,
            attrValues: [commodityAttr[i].attrValueList[j].attrValue]
          });
        }
      }
    }
    // console.log('result', attrValueList) 
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].attrValueStatus) {
          attrValueList[i].attrValueStatus[j] = true;
        } else {
          attrValueList[i].attrValueStatus = [];
          attrValueList[i].attrValueStatus[j] = true;
        }
      }
    }
    this.setData({
      attrValueList: attrValueList
    });
  },
  getAttrIndex: function (attrName, attrValueList) {
    // 判断数组中的attrKey是否有该属性值 
    for (var i = 0; i < attrValueList.length; i++) {
      if (attrName == attrValueList[i].attrKey) {
        break;
      }
    }
    return i < attrValueList.length ? i : -1;
  },
  isValueExist: function (value, valueArr) {
    // 判断是否已有属性值 
    for (var i = 0; i < valueArr.length; i++) {
      if (valueArr[i] == value) {
        break;
      }
    }
    return i < valueArr.length;
  },

  //重新计算
  re_count: function () {
    var total_price = 0.00;
    selectgood.forEach(item => {
      total_price = total_price + parseFloat(item.BuyNum) * parseFloat(item.Price);
    });
    if (selectgood.length > 0) {
      cartpoint = '1'
    } else {
      cartpoint = '0'
    }
    this.setData({
      total_price: total_price,
      cartpoint: cartpoint,
    });
    // console.log(total_price)
  },
  /* 选择属性值事件 */
  selectAttrValue: function (e) {
    /*
    点选属性值，联动判断其他属性值是否可选
    {
      attrKey:'型号',
      attrValueList:['1','2','3'],
      selectedValue:'1',
      attrValueStatus:[true,true,true]
    }
    console.log(e.currentTarget.dataset);
    */
    var attrValueList = this.data.attrValueList;
    var index = e.currentTarget.dataset.index; //属性索引
    var key = e.currentTarget.dataset.key;
    var value = e.currentTarget.dataset.value;
    if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
      if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
        // 取消选中
        this.disSelectValue(attrValueList, index, key, value);
      } else {
        // 选中
        this.selectValue(attrValueList, index, key, value);
      }

    }
    var value1 = [];
    for (var i = 0; i < attrValueList.length; i++) {
      if (!attrValueList[i].selectedValue) {
        break;
      }
      value1.push(attrValueList[i].selectedValue);
    }
    if (i < attrValueList.length) {
      currentNum = selectmap.StoreNum;
      currentPrice = selectmap.Price;

    } else {
      var tempModel = value1.join(';');
      for (var i = 0; i < commodityAttr.length; i++) {
        // console.log(commodityAttr[i].skukey + '11111' + model);
        // console.log(commodityAttr[i].skukey)
        // console.log(tempModel)
        if (commodityAttr[i].skukey == tempModel) {
          currentPrice = commodityAttr[i].price;
          currentNum = commodityAttr[i].stockNum;
        }
      }
    }
    // console.log(commodityAttr)
    // console.log(currentNum)
    this.setData({
      currentNum: currentNum,
      currentPrice: currentPrice,
    })
  },
  /* 选中 */
  selectValue: function (attrValueList, index, key, value, unselectStatus) {
    // console.log('firstIndex', this.data.firstIndex);
    var includeGroup = [];
    if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选
      var commodityAttr = this.data.commodityAttr;
      // 其他选中的属性值全都置空
      // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus);
      for (var i = 0; i < attrValueList.length; i++) {
        for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
          attrValueList[i].selectedValue = '';
        }
      }
    } else {
      var commodityAttr = this.data.includeGroup;
    }

    // console.log('选中', commodityAttr, index, key, value);
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
        if (commodityAttr[i].attrValueList[j].attrKey == key && commodityAttr[i].attrValueList[j].attrValue == value) {
          includeGroup.push(commodityAttr[i]);
        }
      }
    }
    attrValueList[index].selectedValue = value;

    // 判断属性是否可选
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        attrValueList[i].attrValueStatus[j] = false;
      }
    }
    for (var k = 0; k < attrValueList.length; k++) {
      for (var i = 0; i < includeGroup.length; i++) {
        for (var j = 0; j < includeGroup[i].attrValueList.length; j++) {
          if (attrValueList[k].attrKey == includeGroup[i].attrValueList[j].attrKey) {
            for (var m = 0; m < attrValueList[k].attrValues.length; m++) {
              if (attrValueList[k].attrValues[m] == includeGroup[i].attrValueList[j].attrValue) {
                attrValueList[k].attrValueStatus[m] = true;
              }
            }
          }
        }
      }
    }
    // console.log('结果', attrValueList);
    this.setData({
      attrValueList: attrValueList,
      includeGroup: includeGroup
    });

    var count = 0;
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].selectedValue) {
          count++;
          break;
        }
      }
    }
    if (count < 2) { // 第一次选中，同属性的值都可选
      this.setData({
        firstIndex: index
      });
    } else {
      this.setData({
        firstIndex: -1
      });
    }
  },
  /* 取消选中 */
  disSelectValue: function (attrValueList, index, key, value) {
    var commodityAttr = this.data.commodityAttr;
    attrValueList[index].selectedValue = '';

    // 判断属性是否可选
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        attrValueList[i].attrValueStatus[j] = true;
      }
    }
    this.setData({
      includeGroup: commodityAttr,
      attrValueList: attrValueList
    });

    for (var i = 0; i < attrValueList.length; i++) {
      if (attrValueList[i].selectedValue) {
        this.selectValue(attrValueList, i, attrValueList[i].attrKey, attrValueList[i].selectedValue, true);
      }
    }
  },
  /* 点击确定 */
  submit: function (e) {
    if (selectNum <= 0) {
      wx.showToast({
        title: '数量不能为0',
        icon: 'loading',
        duration: 1000
      })
      return;
    }

    if (i < attrValueList.length) {
      wx.showToast({
        title: '请完善属性',
        icon: 'loading',
        duration: 1000
      })
    } else {
      var putString = '';
      for (var i = 0; i < attrValueList.length; i++) {
        if (!attrValueList[i].selectedValue) {
          break;
        }
        if (i == 0) {
          putString = attrValueList[i].attrKey + ',' + attrValueList[i].selectedValue
        } else {
          putString = putString + ';' + attrValueList[i].attrKey + ',' + attrValueList[i].selectedValue
        }
      }
      var model = putString;
      var price1 = '';
      var stockNum1 = '';
      console.log(model)
      for (var i = 0; i < commodityAttr.length; i++) {
        if (commodityAttr[i].skukey == model) {
          GoodsID1 = commodityAttr[i].GoodsID;
          price1 = commodityAttr[i].price;
          stockNum1 = commodityAttr[i].stockNum;
        }
      }
      var flag = '0';
      selectgood.forEach(item => {
        if (selectmap.ID == item.GoodsID) {
          if (item.Model == model) {
            var All = item.stockNum - parseInt(item.BuyNum);
            flag = '1';
            if (item.stockNum < parseInt(item.BuyNum) + selectNum) {
              wx.showModal({
                title: '提示',
                content: '库存不足！您已经添加' + item.BuyNum + '件该类型的产品，最多还可添加' + All + '件',
                showCancel: false
              })
              return;
            }

            item.BuyNum = parseInt(item.BuyNum) + 1;
            wx.showToast({
              title: '添加成功',
              icon: 'sucess',
              duration: 1000

            })
          }
        }
      });
      if (flag == '0') {
        var tempmap = {};
        tempmap.GoodsID = selectmap.ID;
        tempmap.GoodsName = selectmap.GoodsName;
        tempmap.GoodsZsImg = selectmap.ImagesZhanshi;
        tempmap.Price = price1;
        tempmap.BuyNum = selectNum;
        tempmap.Model = model;
        tempmap.stockNum = stockNum1;
        var temparray = [tempmap];
        selectgood = temparray.concat(selectgood)
        wx.showToast({
          title: '添加成功',
          icon: 'sucess',
          duration: 1000

        })
      }
      allGoods.forEach(item => {
        if (item.ID == selectmap.ID) {
          item.isselect = '1';
          item.BuyNum = selectNum;
        }
      });
      this.setData({
        allGoods: allGoods,
        selectNum: selectNum,
      })
      this.re_count(); //重新计算

    }
  },

  // 授权登录
  bindAuthoriza: function () {
    this.setData({
      powerFlag: false
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.pageIndex++
    start = end
    end = this.data.pageIndex * 10
    partarr = partarr.concat(allGoods.slice(start, end))
    this.setData({
      allGoods: partarr
    })
    console.log(partarr);
  },

  // 邮费获取
  MaInput: function (e) {
    this.setData({
      peisongyoufei: e.detail.value,
    })
  },
  // 弹框输入邮费-取消
  cancel1: function () {
    this.setData({
      hiddensubmit1: true,
      peisongyoufei: ""
    });
  },
  // 填写邮费的确定
  confirm1: function (e) {
    var that = this;
    var uid = wx.getStorageSync('uid');
    var buyGoods = '';
    selectgood.forEach(item => {
      if (buyGoods.length < 1) {
        buyGoods = item.GoodsID + "-" + item.BuyNum + "-" + item.Model
      } else {
        buyGoods = buyGoods + "~" + item.GoodsID + "-" + item.BuyNum + "-" + item.Model
      }
    });

    that.setData({
      hiddensubmit1: false,
    })
    setTimeout(function () {
      that.setData({
        peisongyoufei: ""
      })
    }, 1000)
    wx.request({
      url: baseJs.api_Order + "SettlementOrder",
      method: 'post',
      data: baseJs.json2Form({
        UID: uid,
        BuyGoodsInfo: buyGoods,
        PeiSongYouFei: that.data.peisongyoufei,
        IsShouYinJiOrder: '0',
        IsZiTi: '0',
        Remark: '',
      }),
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data)
        var json = res.data.ResultData;
        // console.log(json);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 1000
          });
          setTimeout(function () {
            wx.navigateTo({
              url: '/packageA/OrderQRcode/OrderQRcode?Orderid=' + json.OrderId,
            })
          }, 1000)
        }
        if (res.data.ResultFlag == 0) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
    this.setData({
      hiddensubmit1: true,
      PeiSongYouFei: "",
    });
  },

  // 生成二维码和立即支付-弹框
  surePay: function (e) {
    var that = this;
    if (app.isLogin()) {
      that.setData({
        show: true
      })
    }
  },
  // 客户选择邮寄或者自提
  buttontap(e) {
    var that = this
    var type = e.detail.index
    var uid = this.data.uid
    if (type == 0) {
      console.log("自提");
      // 判断是否在本店铺
      if (that.data.businessId) {
        console.log("跳转订单");
        this.goOrder(1)
      } else {
        console.log("生成二维码");
        this.cancel3()
      }
    } else {
      console.log("邮寄");
      // 判断是否在本店铺
      if (that.data.businessId) {
        console.log("跳转订单");
        this.goOrder(0)
      } else {
        console.log("生成二维码");
        that.setData({
          hiddensubmit1: false,
          show: false
        })
      }

    }
  },
  cancel3: function () { //表示本店铺 跳转到二维码页面
    var uid = wx.getStorageSync('uid');
    var buyGoods = '';
    selectgood.forEach(item => {
      if (buyGoods.length < 1) {
        buyGoods = item.GoodsID + "-" + item.BuyNum + "-" + item.Model
      } else {
        buyGoods = buyGoods + "~" + item.GoodsID + "-" + item.BuyNum + "-" + item.Model
      }
    });
    wx.request({
      url: baseJs.api_Order + "SettlementOrder",
      method: 'post',
      data: baseJs.json2Form({
        UID: uid,
        BuyGoodsInfo: buyGoods,
        PeiSongYouFei: '0',
        IsShouYinJiOrder: '0',
        IsZiTi: '1',
        Remark: '',
      }),

      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data)
        var json = res.data.ResultData;
        // console.log(json);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(function () {
            wx.navigateTo({
              url: '/packageA/OrderQRcode/OrderQRcode?Orderid=' + json.OrderId,
            })
          }, 1000)
        }
        if (res.data.ResultFlag == 0) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }

      }
    })
    this.setData({
      hiddensubmit1: true,
    });

  },

  // 别的商家店铺跳转订单
  goOrder(type) {
    var that = this
    var uid = wx.getStorageSync('uid');
    var buyGoods = '';
    selectgood.forEach(item => {
      if (buyGoods.length < 1) {
        buyGoods = item.GoodsID + "-" + item.BuyNum + "-" + item.Model
      } else {
        buyGoods = buyGoods + "~" + item.GoodsID + "-" + item.BuyNum + "-" + item.Model
      }
    });
    wx.request({
      url: baseJs.api_Order + "SettlementOrder",
      method: 'post',
      data: baseJs.json2Form({
        UID: uid,
        BuyGoodsInfo: buyGoods,
        PeiSongYouFei: '0',
        IsShouYinJiOrder: '0',
        IsZiTi: type,
        Remark: '',
      }),
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          show: false
        })
        var json = res.data.ResultData;
        console.log(json);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 1000
          });

          setTimeout(function () {
            wx.navigateTo({
              url: '/packageA/Orderpayment/Orderpayment?orderid=' + json.OrderId,
            })

          }, 1000)
        }
        if (res.data.ResultFlag == 0) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 1000
          });
        }
      },
      fail: err => {
        console.log(err);
      }
    })
  }
})